package com.study.easyexcel.api.handler;

import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.study.easyexcel.api.annotation.HeadHyperlink;
import org.apache.poi.ss.usermodel.*;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author yuhuan
 * @date 2024/6/12
 */
public class HyperlinkHandler implements CellWriteHandler {

    private final Map<Integer, HeadHyperlink> hyperlinkMap = MapUtils.newHashMap();

    @Override
    public int order() {
        return 50001;
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        Cell cell = context.getCell();
        Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
        int columnIndex = cell.getColumnIndex();
        if (BooleanUtils.isTrue(context.getHead()) && hyperlinkMap.containsKey(columnIndex)) {
            HeadHyperlink headHyperlink = hyperlinkMap.get(columnIndex);
            // 设置超链接
            CreationHelper createHelper = workbook.getCreationHelper();
            Hyperlink hyperlink = createHelper.createHyperlink(headHyperlink.type());
            hyperlink.setAddress(headHyperlink.value());
            cell.setHyperlink(hyperlink);
            setSpecialCellStyle(workbook, cell, headHyperlink);
        }
    }

    public static <T> HyperlinkHandler build() {
        return new HyperlinkHandler();
    }

    /**
     * 定制超链接的专属样式
     **/
    protected void setSpecialCellStyle(Workbook workbook, Cell cell, HeadHyperlink headHyperlink) {
        // 设置单元格的样式
        CellStyle cellStyle = workbook.createCellStyle();
        // 字体
        Font font = workbook.createFont();
        font.setColor(headHyperlink.fontColor().getIndex());
        font.setBold(headHyperlink.fontBold());
        cellStyle.setFont(font);
        // 水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        // 上下居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cell.setCellStyle(cellStyle);
    }

    /**
     * 扫描每个字段上的头部链接编辑器
     *
     * @param pojoClass 要导出的数据
     */
    public <T> HyperlinkHandler scan(Class<T> pojoClass) {
        Field[] declaredFields = pojoClass.getDeclaredFields();
        // 循环每个字段
        for (Field declaredField : declaredFields) {
            boolean isBind = declaredField.isAnnotationPresent(HeadHyperlink.class);
            if (!isBind) {
                continue;
            }
            HeadHyperlink headHyperlink = declaredField.getAnnotation(HeadHyperlink.class);
            this.hyperlinkMap.put(headHyperlink.index(), headHyperlink);
        }
        return this;
    }
}
